import React, { Component, Fragment } from 'react';
import { search } from '../../utils/api';
import { bus } from '../../utils/eventBus';
import '../../style/all.css';
import './SearchList.css';

function resList (res, list, that) {
	if (res === 1) {
		return (
			<Fragment>
				<div className='res_s_list'>
					<h2>
						<span>id</span>
						<span>音乐标题</span>
						<span>歌手</span>
						<span>专辑</span>
						<span>时长</span>
					</h2>
					<ul>
						{list.map((item, index) => (
							<li key={item.id} onClick={() => { bus.emit('syplay', { id: item.id, duration: item.duration, name: item.name, artist: item.artists[0].name }) }}>
								<span>{index + 1}</span>
								<span>{item.name}</span>
								<span className='red' onClick={() => {
									let { offset, searchKeywords, currentPageNum, currentType } = that.state;
									let obj = {
										searchKeywords,
										currentType,
										currentPageNum,
										offset
									}
									sessionStorage.setItem('serachlocation', JSON.stringify(obj));
									that.props.props.history.push(`/search?keywords=${item.artists[0].name}&type=1`)
								}}>{item.artists[0].name}</span>
								<span>{item.album.name}</span>
								<span>{"0" + Math.floor((item.duration / 1000) % 3600 / 60) + ':' + (Math.floor((item.duration / 1000) % 60) < 10 ? '0' + Math.floor((item.duration / 1000) % 60) : Math.floor((item.duration / 1000) % 60))}</span>
							</li>
						))}
					</ul>
				</div>
			</Fragment>
		)
	} else if (res === 1000) {
		return (
			<Fragment>
				<div className='res_g_list'>
					<ul>
						{list.map((item) => (
							<li className='perse25' key={item.id} onClick={() => {
								let { offset, searchKeywords, currentPageNum, currentType } = that.state;
								let obj = {
									searchKeywords,
									currentType,
									currentPageNum,
									offset
								}
								sessionStorage.setItem('serachlocation', JSON.stringify(obj));
								that.props.props.history.push(`/gedandetail?id=${item.id}`)
							}}>
								<div className='img tophover'>
									<img width='100%' height='100%' src={item.coverImgUrl} alt="" />
									<div className='gd_mv_hover'></div>
								</div>
								<p>{item.name}</p>
							</li>
						))}
					</ul>
				</div>
			</Fragment>)
	} else {
		return (
			<Fragment>
				<div className='res_m_list'>
					<ul className='box'>
						{list.map((item) => (
							<li className='perse25' key={item.id} onClick={() => { that.props.props.history.push(`/mvdetail?id=${item.id}`) }}>
								<div className='img tophover'>
									<img width='100%' height='100%' src={item.cover} alt="" />
									<div className='gd_mv_hover'></div>
								</div>
								<p><span>{item.name}</span><br /><span>{item.artists[0].name}</span></p>
							</li>
						))}
					</ul>
				</div>
			</Fragment>
		)
	}
}

export default class SearchList extends Component {
	state = {
		searchKeywords: (JSON.parse(sessionStorage.getItem('serachlocation')) && JSON.parse(sessionStorage.getItem('serachlocation')).searchKeywords) || '',
		count: 0,
		currentType: (JSON.parse(sessionStorage.getItem('serachlocation')) && JSON.parse(sessionStorage.getItem('serachlocation')).currentType) || 1,
		limit: 20,
		offset: (JSON.parse(sessionStorage.getItem('serachlocation')) && JSON.parse(sessionStorage.getItem('serachlocation')).offset) || 0,
		searchList: [],
		currentPageNum: (JSON.parse(sessionStorage.getItem('serachlocation')) && JSON.parse(sessionStorage.getItem('serachlocation')).currentPageNum) || 1,
	}
	componentDidMount () {
		this.firstSearch();
	}
	async firstSearch () {
		var { limit, offset, searchKeywords, currentType } = this.state;
		var searchList;
		if (!JSON.parse(sessionStorage.getItem('serachlocation'))) {
			var query = this.props.props.location.search.split('&');
			var arr = [];
			for (var i = 0; i < query.length; i++) {
				arr.push(query[i].split('=')[1]);
			}
			var [keywords, type] = arr;
			searchList = await search(keywords, limit, offset, type);
		} else {
			type = currentType;
			keywords = searchKeywords;
			searchList = await search(searchKeywords, limit, offset, currentType);
		}
		let result;
		let resultCount;
		if (Number(type) === 1) {
			result = ["songs"];
			resultCount = ["songCount"];
		} else if (Number(type) === 1000) {
			result = ["playlists"];
			resultCount = ["playlistCount"];
		} else {
			result = ['mvs'];
			resultCount = ['mvCount'];
		}
		this.setState({
			currentType: Number(type),
			searchKeywords: keywords,
			searchList: searchList.result[result],
			count: searchList.result[resultCount]
		})
	}
	async changeType (type) {
		let { limit, searchKeywords } = this.state;
		const searchList = await search(searchKeywords, limit, 0, type);
		let result;
		let resultCount;
		if (type === 1) {
			result = ["songs"];
			resultCount = ["songCount"];
		} else if (type === 1000) {
			result = ["playlists"];
			resultCount = ["playlistCount"];
		} else {
			result = ['mvs'];
			resultCount = ['mvCount'];
		}
		this.setState({
			currentType: type,
			searchKeywords: searchKeywords,
			searchList: searchList.result[result],
			count: searchList.result[resultCount],
			offset: 0,
			currentPageNum: 1
		})
	}
	goNext = async () => {
		let { limit, offset, searchKeywords, currentPageNum, currentType } = this.state;
		const searchList = await search(searchKeywords, limit, offset + limit, currentType);
		let result;
		let resultCount;
		if (currentType === 1) {
			result = ["songs"];
			resultCount = ["songCount"];
		} else if (currentType === 1000) {
			result = ["playlists"];
			resultCount = ["playlistCount"];
		} else {
			result = ['mvs'];
			resultCount = ['mvCount'];
		}
		this.setState({
			currentType: currentType,
			searchKeywords: searchKeywords,
			searchList: searchList.result[result],
			count: searchList.result[resultCount],
			offset: offset + limit,
			currentPageNum: currentPageNum + 1
		})
	}
	goPrev = async () => {
		let { limit, offset, searchKeywords, currentPageNum, currentType } = this.state;
		const searchList = await search(searchKeywords, limit, offset - limit, currentType);
		let result;
		let resultCount;
		if (currentType === 1) {
			result = ["songs"];
			resultCount = ["songCount"];
		} else if (currentType === 1000) {
			result = ["playlists"];
			resultCount = ["playlistCount"];
		} else {
			result = ['mvs'];
			resultCount = ['mvCount'];
		}
		this.setState({
			currentType: currentType,
			searchKeywords: searchKeywords,
			searchList: searchList.result[result],
			count: searchList.result[resultCount],
			offset: offset - limit,
			currentPageNum: currentPageNum - 1
		})
	}
	render () {
		let { currentType, searchList, searchKeywords, count, currentPageNum, limit } = this.state;
		return (
			<div className='search main'>
				<div className='search_title'>
					<h2>{searchKeywords}</h2>
					<span>共找到 {count} 个结果</span>
				</div>
				<div className='search_res'>
					<div className='toggle_tag'>
						<ul>
							<li onClick={() => { this.changeType(1); }} className={currentType === 1 ? 'active' : ''}>歌曲</li>
							<li onClick={() => { this.changeType(1000); }} className={currentType === 1000 ? 'active' : ''}>歌单</li>
							<li onClick={() => { this.changeType(1004); }} className={currentType === 1004 ? 'active' : ''}>MV</li>
						</ul>
					</div>
					{resList(currentType, searchList, this)}
					<div className='page'>
						{currentPageNum < 2 ? null : <span onClick={this.goPrev}>&lt;前往上一页</span>}
						{(Math.ceil(count / limit)) <= currentPageNum ? null : <span onClick={this.goNext}>前往下一页&gt;</span>}
					</div>
				</div>
			</div>
		)
	}
}
